package com.luo.d3s.ext.event.jdbc.receive;

import com.luo.d3s.core.domain.event.DomainEvent;
import com.luo.d3s.ext.event.jdbc.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 内部领域事件分发器
 *
 * @author luohq
 * @date 2023-01-24 16:37
 */
@Component
public class InternalDomainEventHandler {

    private static final Logger log = LoggerFactory.getLogger(InternalDomainEventHandler.class);

    @EventListener
    public void receiveEvent(PayloadApplicationEvent payloadApplicationEvent) {
        try {
            log.debug("Receive internal event: {}", payloadApplicationEvent);
            if (payloadApplicationEvent.getPayload() instanceof DomainEvent) {
                DomainEvent domainEvent = (DomainEvent) payloadApplicationEvent.getPayload();
                EventBus.dispatchBatch(domainEvent);
            }
        } catch (Throwable ex) {
            log.error("Dispatch internal event exception!", ex);
        }
    }
}
